<!-- 转正申请 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
      	fontSize: '14px',
      	color: '#B2B2B2',
      	lineHight: '20px'
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
				<u-form-item label="单据编号" prop="billNo">
				  <u--input disabled placeholder="请输入单据编号" v-model="model.billNo"></u--input>
				</u-form-item>
        <u-form-item label="申请人" prop="employeeId">
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.employeeId"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.employeeId"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="人员编号" prop="employeeNo">
          <u--input disabled placeholder="请输入人员编号" v-model="model.employeeNo"></u--input>
        </u-form-item>
        <u-form-item label="性别" prop="gender">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.gender"
            objectField="model.gender"
            placeholder="请选择性别"
            border="surround"
            dictName="gender"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="出生日期" prop="birthday">
          <h-time-select
            disabled
            mode="datetime"
            ref="remittanceDate"
            v-model="model.birthday?moment(model.birthday).format('YYYY-MM-DD'):model.birthday"
            placeholder="请选择出生日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
				<u-form-item label="岗位序列" prop="positionCategory">
				  <h-select-input-tag
				    class="w-100"
						disabled
				    v-model="model.positionCategory"
				    objectField="model.positionCategory"
				    placeholder="请选择岗位序列"
				    border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
				    dictName="position_category"
				  ></h-select-input-tag>
				</u-form-item>
        <u-form-item label="岗位名称" prop="positionId">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.positionId"
            objectField="model.positionId"
            placeholder="请选择岗位名称"
            border="surround"
            dictName="sys_position,name,id,del_flag = 0 and audit_status=2"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="毕业院校" prop="graduatedFrom">
          <u--input disabled placeholder="请输入毕业院校" v-model="model.graduatedFrom"></u--input>
        </u-form-item>
        <u-form-item label="学历" prop="highestDegree">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.highestDegree"
            objectField="model.highestDegree"
            placeholder="请选择学历"
            border="surround"
            dictName="highest_degree"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="所学专业" prop="major">
          <u--input disabled placeholder="请输入所学专业" v-model="model.major"></u--input>
        </u-form-item>
        <u-form-item label="毕业时间" prop="graduationDate">
          <h-time-select
            disabled
            mode="date"
            v-model="model.graduationDate?moment(model.graduationDate).format('YYYY-MM-DD'):model.graduationDate"
            placeholder="请选择毕业时间"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="所在部门" prop="departmentId">
          <h-select-depart-input
            disabled
            v-model="model.departmentId"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="入职日期" prop="entryTime" required>
          <h-time-select
            disabled
            mode="datetime"
            v-model="model.entryTime?moment(model.entryTime).format('YYYY-MM-DD'):model.entryTime"
            placeholder="请选择入职日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="职称" prop="professionalTitle">
          <u--input disabled placeholder="请输入职称" v-model="model.professionalTitle"></u--input>
        </u-form-item>
        <u-form-item label="职业资格" prop="professionalQualification" required>
          <u--input placeholder="请输入职业资格" v-model="model.professionalQualification" :maxlength="100"></u--input>
        </u-form-item>
        <u-form-item label="所属团队" prop="teamId" required>
          <h-select-team-input
            disabled
            style="width: 100%"
            v-model="model.teamId"
            objectField="model.teamId"
            placeholder="请选择所属团队"
            border="surround"
            :tdlx="3"
          />
        </u-form-item>
        <u-form-item label="非相关工作经验（年）" prop="workExperience">
          <u--input placeholder="请输入非相关工作经验（年）" v-model="model.workExperience" :maxlength="10"></u--input>
        </u-form-item>
        <u-form-item label="相关工作经验（年）" prop="relatedWorkExperience" required>
          <u--input placeholder="请输入相关工作经验（年）" v-model="model.relatedWorkExperience" :maxlength="10"></u--input>
        </u-form-item>
        <u-form-item label="申请转正日期" prop="regularTime" required>
          <h-time-select
            mode="date"
            v-model="model.regularTime"
            placeholder="请选择申请转正日期"
            border="surround"
            suffixIcon="calendar-fill"
						:minDate="model.entryTime?(new Date(model.entryTime)).getTime():315504000000"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="试用期工资标准(元)" prop="salary">
          <u--input type="number" v-number-normal placeholder="请输入试用期工资标准(元)" v-model="model.salary" disabled></u--input>
        </u-form-item>
        <u-form-item label="预计转正后薪级" prop="regularScale">
          <h-select-input-tag
						disabled
            class="w-100"
            v-model="model.regularScale"
            objectField="model.regularScale"
            placeholder="请选择预计转正后薪级"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="erp_pay_grade,salary_grade,id,del_flag = 0 and audit_status=2"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="转正后确认薪级" prop="salaryScale">
          <h-select-input-tag
						disabled
            class="w-100"
            v-model="model.salaryScale"
            objectField="model.salaryScale"
            placeholder="请选择转正后确认薪级"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="erp_pay_grade,salary_grade,id,del_flag = 0 and audit_status=2"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="公积金基数(元)" prop="providentFundBase">
          <u--input type="number" v-number-normal placeholder="请输入公积金基数(元)" disabled v-model="model.providentFundBase"></u--input>
        </u-form-item>
        <u-form-item label="公积金购买单位" prop="providentFundUnit">
          <h-select-company-input-popup
						disabled
            style="width: 100%"
            v-model="model.providentFundUnit"
            placeholder="请选择公积金购买单位"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-company-input-popup>
        </u-form-item>
        <u-form-item label="其他约定事项" prop="remark">
          <u--textarea :confirm-type="null" count :maxlength="500" v-model="model.remark" placeholder="请输入其他约定事项"></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">相关附件</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.attachment" :isIcon="false"></h-upload-file>
          <file-list v-if="model.attachment" v-model="model.attachment" :isDelete="true"></file-list>
        </view>
      </view>

			<view class="space-x-1 px-1 btn_position">
				<u-button :disabled="isSubmit" type="primary" :plain="true" text="保存草稿" @click="onDraft"></u-button>
				<u-button :disabled="isSubmit"  type="primary"  text="保存并提交" @click="onSubmit"></u-button>
			</view>
			<view style="height: 100rpx;"></view>
    </u-form>
		<u-toast ref="uToast"></u-toast>
		<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { add, info, queryPostRecordByInfo,edit } from '@/api/hr/EmploeeRegularApply'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
import fileList from '@/pages/synergy/components/fileList.vue'
import http from '@/utils/request/index'
export default {
  name: 'EmploeeRegularApply',
  components: {
    fileList,
		ProcessNodeConfiguration
  },
  data() {
    const validatorFlag = async (rule, value, callback) => {
      if (value) {
        const that = this
        if (!this.flag) {
          callback('请保存试用期考核表！')
          return
        }
        callback()
      }
      callback()
    }
    return {
			moment,
      backUpProvisionBroad: '',
      showBusinessSegment: false,
      exportTeamId: '',
      flag: false,
      index: null,
      showFormModal: false,
      confirmModal: false,
      loading: false,
      id: '',
      exportWarehouseList: [],
      foldWarehouseList: [],
      dataSource2: [],
      basicForm: {},
      formData: [],
      model: {
				billNo: '',
        employeeId: '',
        employeeNo: '',
        gender: '',
        birthday: '',
				positionCategory: '',
        positionId: '',
        graduatedFrom: '',
        highestDegree: '',
        major: '',
        graduationDate: '',
        departmentId: '',
        entryTime: '',
        professionalTitle: '',
        professionalQualification: '',
        teamId: '',
        workExperience: '',
        relatedWorkExperience: '',
        regularTime: '',
        salary: '',
        regularScale: '',
        salaryScale: '',
        providentFundBase: '',
        providentFundUnit: '',
        remark: '',
        attachment: null,
      },
      rules: {
        relatedWorkExperience: [{ required: true, message: '请输入相关工作经验!' }],
        // salary: [{ type: 'number', required: true, message: '请输入试用期工资标准!' }],
				entryTime: [{ required: true, message: '请选择入职日期!' }],
        professionalQualification: [{ required: true, message: '请输入职业资格!' }],
        // salary: [
        //   { required: true, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的试用期工资标准!' },
        // ],
        teamId: [{ required: true, message: '请选择所属团队!' }],
        bpmBizTitle: [{ required: true, message: '请输入流程标题!' }],
        entryTime: [{ required: true, message: '您暂无入职日期，请联系HR!' }],
        probationership: [{ required: true, message: '请选择试用期限!' }],
        regularTime: [{ required: true, message: '请选择申请转正日期!' }],
        appraiser: [{ required: true, message: '请选择评价人!' }],
        appraiseScore: [{ required: true, message: '请选择试用期打分!' }],
        evaluationPeriod: [{ required: true, message: '请输入试用期评价!' }],
        improvementItems: [{ required: true, message: '请输入需改进事项!' }],
        regularDetail: [{ required: true, message: '请完善员工试用期考核表!' }, { validator: validatorFlag }],
      },
			isSubmit: false,
			//代码生成后需手动设置流程编码
			flowCode: 'onl_erp_hr_employee_regular_bill',
			formUrl: "erp/hr/regular/modules/ErpHrEmployeeRegularBillForm",
			formUrlMobile: "/pages/synergy/erpHrEmployeeRegularBillList",
			processId:"1540233415628972033",
			beanName:"erpHrEmployeeRegularBillServiceImpl"
    }
  },
  onLoad({ id }) {
    this.id = id || ''
		if (this.id) {
		  this.initInfo()
		} else {
		  this.initForm()
			this.generatedFormNumber()
		}
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
		// 获取编号
		generatedFormNumber() {
			http.get('/api/erp/base/generatedFormNumber', { prefix: 'ZZ', subSystemCode: '02' }).then(res => {
				if (res.success) {
					this.$set(this.model, 'billNo', res.result)
				}
			})
		},
		// 获取流程列表
		getProcessList (id) {
			if (this.isSubmit) {
				this.$refs.processConfig.showPopup = true
				this.$refs.processConfig.formUrl = this.formUrl
				this.$refs.processConfig.formUrlMobile = this.formUrlMobile
				this.$refs.processConfig.flowCode = this.flowCode
				this.$refs.processConfig.edit(id, this.processId, this.beanName)
			}
		},
		// 提交流程成功
		onOk () {
			this.$refs.uToast.show({
				message: '提交成功',
				type: 'success',
				complete () {
					if (getCurrentPages().length > 1) {
						uni.navigateBack()
					} else {
						uni.reLaunch({
							url: '/pages/home/home'
						})
					}
					
				}
			})
		},
    /**
     * 弹窗点击确认
     */
    handleConfirmModalConfirm() {
      this.formData = []
      this.confirmModal = false
    },
    /**
     * 弹窗点击取消
     */
    handleConfirmModalCancel() {
      // 还原修改的数据
      if (this.resetKey) {
        let realKey = this.resetKey.replace('backUp', '')
        realKey = realKey[0].toLowerCase() + realKey.slice(1)
        this.isReset = true
        this.$set(this.model, realKey, this[this.resetKey])
        setTimeout(() => (this.isReset = false), 0)
      }
      this.confirmModal = false
    },
    /**
     * 修改值时，检查是否需要弹出对话框确认修改
     * 取消 modal 的时候，需要将值还原
     * @param {String} key BasicForm 中的key值
     * @param {Function} fn 回调函数
     * @param {any} data 回调函数参数
     */
    checkSwitch(key, fn, data) {
      this.$nextTick(() => {
        if (this.isReset) return
        const firstChar = key[0].toUpperCase()
        key = firstChar + key.slice(1)
        const oldData = this[`backUp${key}`]
        if (oldData && oldData !== this.model[key]) {
          this.confirmModal = true
          this.resetKey = `backUp${key}`
        } else {
          fn && fn(data)
        }
      })
    },
    projectChange() {},
    handleChangeFoldTeamId(val, num = 0) {
      let v = val.id
      this.foldTeamIdChange(v, num)
    },
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
    foldTeamIdChange(id, edit) {
      if (this.model.exportTeamId == id) {
        this.$u.toast('调入团队不能和调出团队相同')
        this.$set(this.model, 'foldTeamId', null)
        this.$set(this.model, 'foldWarehouse', undefined)
        return false
      }
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.foldWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'foldWarehouse', undefined)
          }
          const data = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.foldWarehouseList = [data]
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 新增物料
    handleAddMaterial() {
      if (!this.model.provisionBroad) {
        this.$u.toast('请先选择采购大类')
        return false
      }
      this.index = null
      this.showFormModal = true
    },
    handleChangeExportTeamId(v, num = 0) {
      if (v != this.exportTeamId) {
        this.exportTeamIdChange(v, num)
      }
      this.exportTeamId = this.model.exportTeamId
    },
    /**
     * 调出团队 change 事件
     * @param {Object} row 选中的团队
     * @param {Boolean} edit false 时清空 warehouse 和 exprortWareHouse
     */
    exportTeamIdChange(row, edit = false) {
      const id = row.id
      if (this.model.foldTeamId == id) {
        this.model.exportTeamId = this.exportTeamId
        this.$u.toast('调入团队不能和调出团队相同')
        return false
      }
      // 清空子表
      // this.$refs.cannibalizeDetailList.reset()
      this.warehouse = null
      queryByDepartment({ department: id }).then((res) => {
        if (res.success) {
          this.exportWarehouseList = []
          if (!edit) {
            this.$set(this.model, 'exportWarehouse', undefined)
            this.warehouse = null
          }
          const list = res.result.map((res) => {
            return { id: res.id, categoryName: res.storehouseName }
          })
          this.exportWarehouseList = [list]
        } else {
          this.$u.toast(res.message)
        }
      })
    },
    handleCopyForm([item, index]) {
      this.formData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
    },
    openFormModal() {
      this.$refs.dataForm.basicForm = this.basicForm
    },
    addForm() {
      this.index = null
      this.showFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, data)
      } else {
        this.formData.push(data)
      }
    },
    // 初始化新增需要的数据
    initForm() {
      const userInfo = this.userInfo
      this.$set(this.model, 'employeeId', userInfo.empId)
      this.$set(this.model, 'employeeNo', userInfo.employee.employeeNo)
      //this.$set(this.model,'workUnit',userInfo.employee.orgDepart);
      this.$set(this.model, 'departmentId', userInfo.deptId)
      // this.$set(this.model,'teamId',userInfo.employee.teamId);
      //this.$set(this.model,'positionId',userInfo.employee.mainPost);
      this.$set(this.model, 'entryTime', userInfo.employee.joinDate)
      this.$set(this.model, 'gender', userInfo.employee.gender)
      this.$set(this.model, 'birthday', userInfo.employee.birthDate)
      this.$set(this.model, 'graduatedFrom', userInfo.employee.graduatedFrom)
      this.$set(this.model, 'highestDegree', userInfo.employee.highestDegree)
      this.$set(this.model, 'major', userInfo.employee.major)
      this.$set(this.model, 'graduationDate', userInfo.employee.graduationDate)
      this.$set(this.model, 'professionalTitle', userInfo.employee.professionalTitle)
      this.$set(this.model, 'bpmBizTitle', userInfo.employee.name)

      queryPostRecordByInfo({
        employeeId: userInfo.empId,
        departId: userInfo.deptId,
      }).then((res) => {
        if (res.success) {
					this.$set(this.model, 'positionCategory', res.result[0].positionCategory);
          this.$set(this.model, 'positionId', res.result[0].postCode)
          this.$set(this.model, 'teamId', res.result[0].teamId)
        } else {
          this.$u.toast(res.message)
        }
      })
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
			this.model = await Object.assign({}, data)
    },
    validateForm() {
      return this.$refs.form.validate()
    },
    async onSubmit() {
      await this.validateForm()
			this.isSubmit = true
			try {
			  this.loading = true
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
			  const response = await url(this.model)
			  this.$u.toast(response.message)
			  if (response.success) {
			    var that = this
			    
			    // 获取流程列表
			    if (this.model.id) {
			    	this.getProcessList(this.model.id)
			    } else {
			    // 判断添加的时候是否有返回id值
			    	if (response.result) {
			    		this.getProcessList(response.result)
			    	}
			    
			    }
			    this.$refs.uToast.show({
			    	message: response.message,
			    	type: 'default',
			    	complete () {
			    		// that.isSubmit = false
			    	}
			    })
			  }else {
					this.isSubmit = false
					this.$refs.uToast.show({
						message: response.message,
						type: 'error'
					})
				}
			} finally {
			  this.loading = false
			}
    },
    async onDraft() {
      // await this.validateForm()
			this.isSubmit = true
			try {
			  this.loading = true
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
			  const response = await url(this.model)
			  if (response.success) {
					this.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete () {
							this.isSubmit = false
							if (getCurrentPages().length > 1) {
								uni.navigateBack()
							} else {
								uni.reLaunch({
									url: '/pages/home/home'
								})
							}
							
						}
					})
			  } else {
					this.isSubmit = false
					this.$refs.uToast.show({
						message: response.message,
						type: 'error'
					})
				}
			} finally {
			  this.loading = false
			}
    },
  },
  watch: {
    tenderFormData: {
      immediate: true,
      handler(val) {
        if (val?.length) {
          const total = val.reduce((total, item) => {
            return total + item.amount * item.budgetAmount
          }, 0)
          this.$set(this.model, 'projectBudget', String(total))
        } else {
          this.$set(this.model, 'projectBudget', String(0))
        }
      },
    },
    'model.provisionBroad'(current, old) {
      if (old && current && old !== current) {
        this.backUpProvisionBroad = old
      }
    },
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
